<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 2020-06-18
 * Time: 18:48
 */

namespace app\api\service\coupon;


use app\api\model\Coupon;
use app\api\model\CouponUse;
use app\api\service\Token;
use app\lib\exception\ParameterException;
use think\Db;
use think\Exception;

class CouponSer extends Token
{
    /**
     * 1.获取用户信息
     * 2.获取优惠券信息
     * 3.判断优惠劵信息
     * 4.减数量 添加领取优惠券信息
     */

    // 用户ID
    private $uid;

    private $couponId;

    function __construct($couponId)
    {
        $this->uid = self::getCurrentUid();
        $this->couponId = $couponId;
    }

    public function entrance()
    {
        return $this->judgeCoupon();
    }

    // 获取优惠券  判断优惠券信息
    private function judgeCoupon()
    {
        $info = Coupon::get($this->couponId);
        if(!$info) {
            throw new ParameterException([
                'msg' => [
                    'coupon' => '请重新选择优惠券'
                ]
            ]);
        }
        $time = time();
        if($time > $info['end_time']) {
            throw new ParameterException([
                'msg' => [
                    'coupon' => '优惠券已过期'
                ]
            ]);
        }
        if($info['number'] <= 0) {
            throw new ParameterException([
                'msg' => [
                    'coupon' => '优惠券数量不足'
                ]
            ]);
        }
        $couponUse = CouponUse::where('coupon_id',$this->couponId)->where('user_id',$this->uid)->find();
        if($couponUse) {
            throw new ParameterException([
                'msg' => [
                    'coupon' => '您已经领取过'
                ]
            ]);
        }
        return $this->createData();
    }

    // 创建数据
    private function createData()
    {
        Db::startTrans();
        try{
            CouponUse::create([
                'user_id' => $this->uid,
                'coupon_id' => $this->couponId,
            ]);
            Coupon::where('id',$this->couponId)->setDec('number',1);
            Db::commit();
            return writeJson(201, [], '领取成功！');
        }
        catch (Exception $ex) {
            //回滚事务
            Db::rollback();
            throw $ex;
        }
    }
}